<?php

namespace App\Http\Controllers\Admin\Wechat\Manager;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Wechat\User;

class UserController extends AdminController
{
    /**
     * 获取列表数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function getLists(Request $request ){
    	$pageIndex = (int)$request->input('page') ?  $request->input('page') : 1;
        $length    = (int)$request->input('length') ?  $request->input('length') : 10;
        $start     = ($pageIndex-1)*$length;

    	$where = [];
        $subscribe = $request->input('subscribe');
        if($subscribe>-1){
            $where ['subscribe'] = $subscribe;
        }
        $userModel = User::where($where);
        $name = $request->input('name');
        if($name){
            $userModel = $userModel
            ->where('nickname', 'like', "%$name%")
            ->orWhere('openid','like', "%$name%")
            ->orWhere('remark','like', "%$name%");
        }

    	$data['total'] = $userModel->count();
    	if($data['total']>0){
    		$data['result'] = $userModel->orderBy('subscribeTime','desc')->skip($start)->take($length)->get()->toArray();
    	}
    	$this->ajaxJson(0,'',$data);
    }

    /**
     * 同步微信用户
     * @return [type] [description]
     */
    function asyncUser(Request $request){
        $appUser = app('wechat.official_account')->user;
        $nextOpenid = $request->input('nextOpenid');
        $error    = config('wechaterrorcode');
        try {
            $wechatUsers = $appUser->list($nextOpenid ? $nextOpenid : '');
        } catch (\Exception $e) {
            $code = $e->formattedResponse['errcode'];
            $this->ajaxJson(1,'同步异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $e->formattedResponse['errmsg']));
        }
        if(isset($wechatUsers['errcode'])){
            $this->ajaxJson(1,'同步失败'.(array_key_exists($wechatUsers['errcode'],$error)==true ? $error[$wechatUsers['errcode']] : $wechatUsers['errmsg']));
        }
        if($wechatUsers['next_openid']==''){
            $this->ajaxJson(0,'同步已全部完成');
        }

        foreach ($wechatUsers['data']['openid'] as $openid) {
            $wechatUser = $appUser->get($openid);
            $user = User::where('openid',$openid)->first();
            if(!$user){
                $user = new User();
                $user->openid = $openid;
            }
            if(!$wechatUser['subscribe']){
                $user->subscribe = 0 ;
            }else{
                $user->openid = $wechatUser['openid'];
                $user->nickname = $wechatUser['nickname'];
                $user->sex = $wechatUser['sex'];
                $user->province = $wechatUser['province'];
                $user->city = $wechatUser['city'];
                $user->country = $wechatUser['country'];
                $user->headimgurl = $wechatUser['headimgurl'] ? explode('/132', $wechatUser['headimgurl'])[0] : '';
                $user->subscribe = $wechatUser['subscribe'];
                $user->subscribeTime = date('Y-m-d H:i:s',$wechatUser['subscribe_time']);
                $user->remark = $wechatUser['remark'];
                $user->unionid = isset($wechatUser['unionid']) ?  $wechatUser['unionid'] : '';
                $user->groupid = $wechatUser['groupid'];
                $user->tagid_list = empty($user['tagid_list']) ? '': implode(',',$user['tagid_list']);
            }
            $user->save();
        }
        $this->ajaxJson(0,'同步成功',['next_openid'=>$wechatUsers['next_openid']]);
    }

    /**
     * 更新微信备注
     * @return [type] [description]
     */
    function updateRemark(Request $request){
        $user = $this->_get_one($request->input('id'));
        $openid = $user->openid;
        $remark = $request->input('remark');
        $result = app('wechat.official_account')->user->remark($openid,$remark);
        if(!$result){
            $this->ajaxJson(1,'修改备注失败,请确认公众号权限');
        }
        $user->remark = $remark;
        $user->save();
        $this->ajaxJson(0,'修改成功');
    }

    /**
     * 更新用户标签
     * @return [type] [description]
     */
    function updateTag(Request $request){
        // $app     = app('wechat.official_account')->user;
        // $openids = array_pluck($request->input('data'),'openid');
        // $tag_id  = $request->input('tag_id');
        // $result  = $app->tagUsers($openids,$tag_id);
        // $users   = $app->select($openids);
        // if($result){
        //     try {
        //         DB::beginTransaction();

        //         DB::commit();
        //         $this->ajaxJson(0,'更新成功');
        //     } catch (Exception $e) {
        //         DB::rollback();
        //         Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
        //         $this->ajaxJson(1,'更新失败');
        //     }
        // }else{
        //     $this->ajaxJson(1,'更新失败,请确认公众号权限');
        // }
    }

    private function _get_one($id){
        $user = User::find($id);
        if(!$user){
            $this->ajaxJson(1,'更新的数据不存在');
        }
        return $user;
    }
}
